package com.zcc.servlet;

import com.zcc.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter out = resp.getWriter();

        //获取Session
        HttpSession session = req.getSession();

        //给Session当中存东西
        session.setAttribute("name","郑冲冲");
        session.setAttribute("person",new Person("郑冲冲",1));
        //session.setAttribute("person","郑冲冲");

        //从Session中获取内容
        //获取Session的ID
        String sessionId = session.getId();

        //判断Session是否为新建
        if(session.isNew()){
            out.write("Session创建成功，ID："+sessionId);
        }else {
            out.write("Session已经在服务器中存在，ID："+sessionId);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
